package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ClassName: GlobalExceptionHandler
 * Package: com.qk.exception
 * Description:
 *
 * @Author zt
 * @Create 2025/7/28 9:16
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handle(Exception e) {
        log.error("服务器异常", e);
        return Result.error("对不起，您的网络有问题，请稍后重试！");
    }

    /*
    捕获 DuplicateKeyException
     */
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        String errMsg = e.getMessage();
        if (errMsg.contains("Duplicate entry")){
            String msg = errMsg.substring(errMsg.lastIndexOf("Duplicate entry"));
            String[] arr = msg.split(" ");
            return Result.error("用户名" + arr[2] + "已存在");
        }

        return Result.error("对不起，服务器异常，请稍后重试！");
    }

    @ExceptionHandler
    public Result handleBusinessException(BusinessException e) {
        log.error("程序运行错误", e);
        return Result.error(e.getMessage());
    }

}
